import numpy as np

# 加载Iris数据集
def load_iris_dataset():
    url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
    data = np.genfromtxt(url, delimiter=',', dtype='str')
    X = data[:, :-1].astype(float)
    y = data[:, -1]
    return X, y

# 计算两个样本之间的欧几里得距离
def euclidean_distance(x1, x2):
    return np.sqrt(np.sum((x1 - x2)**2))

# K最近邻算法
def k_nearest_neighbors(X_train, y_train, x_test, k=3):
    distances = [euclidean_distance(x_test, x) for x in X_train]
    indices = np.argsort(distances)[:k]
    k_nearest_labels = [y_train[i] for i in indices]
    unique_labels, counts = np.unique(k_nearest_labels, return_counts=True)
    predicted_label = unique_labels[np.argmax(counts)]
    return predicted_label

# 主函数
def main():
    # 加载数据集
    X, y = load_iris_dataset()

    # 划分数据集为训练集和测试集
    split_ratio = 0.8
    split_index = int(split_ratio * len(X))
    X_train, X_test = X[:split_index], X[split_index:]
    y_train, y_test = y[:split_index], y[split_index:]

    # 预测测试集的标签
    predictions = [k_nearest_neighbors(X_train, y_train, x_test) for x_test in X_test]

    # 打印预测结果和实际标签
    print("预测分类:", predictions)
    print("实际分类:", y_test.tolist())

    # 计算准确率
    accuracy = np.mean(predictions == y_test)
    print(f'准确率: {accuracy * 100:.2f}%')

if __name__ == "__main__":
    main()
